package cn.loan.spring.web;

import cn.loan.spring.SpringRootConfigure;
import cn.loan.spring.mvc.SpringMvcConfig;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.FrameworkServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * @Author: 毛苏宇
 * @Description: 相当于web.xml配置
 * @Date: Create in 11:50 2019/4/26
 */
public class WebXmlConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    /**
     * 加载Spring配置
     *
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringRootConfigure.class};
    }

    /**
     * webmvc配置
     *
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    /**
     * 配置DispatcherServlet前端控制器
     *
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }


    /**
     * 启用@ControllerAdvice,@ExceptionHandler(Exception.class)注解的异常捕捉功能
     * @param servletAppContext
     * @return
     */
    @Override
    protected FrameworkServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
        final DispatcherServlet dispatcherServlet = new DispatcherServlet(){
            /**
             * 重新设置应用程序上下文
             */
            {
                setApplicationContext(servletAppContext);
            }
        };
        /**
         * 当找不到该请求的处理程序时,默认由servlet进行处理,如抛出404和500.
         * 当设置为true时可以自定义处理异常请求
         */
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        return dispatcherServlet;
    }

}
